package main

import (
	"fmt"
	"sync"
	"time"
)

type Message struct {
	Devuuid string
	Content string
}

var (
	messageChannel = make(chan Message)
	mergedMessages = sync.Map{}
)

func mainmer() {
	// 模拟不同时间收到的消息
	go func() {
		var i int
		for {
			if i < 5 {
				messageChannel <- Message{Devuuid: "00030200", Content: fmt.Sprintf("Notification %d", i)}
				// time.Sleep(2 * time.Second) // 模拟不同时间收到的消息
				i++
			} else {
				i = 0
			}
		}
	}()

	// 定时器，每分钟处理一次消息合并
	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case msg := <-messageChannel:
			// 合并相同类型的消息
			if _, ok := mergedMessages.Load(msg.Devuuid); !ok {
				fmt.Println("msg.Devuuid =====", msg.Devuuid)
				mergedMessages.Store(msg.Devuuid, msg.Content)
			}
		case <-ticker.C:
			// 发送合并后的消息
			mergedMessages.Range(walk)
		}
	}
}

func walk(msgType, content interface{}) bool {
	fmt.Printf("Merged message - Type: %s, Content: %s", msgType, content, time.Now().Unix())
	mergedMessages.Delete(msgType)
	return true
}
